package main

import (
	"fmt"
	"math/rand"

	"main/role"
)

type Game struct {
	players Players
}

func NewGame() *Game {
	return &Game{
		players: createPlayers(),
	}
}

func createPlayers() Players {
	roles := make([]role.Role, 0)
	for i := 0; i < 4; i++ {
		roles = append(roles, role.NewVillager())
	}
	for i := 0; i < 3; i++ {
		roles = append(roles, role.NewWerewolf())
	}
	roles = append(roles, role.NewWitch())
	roles = append(roles, role.NewSeer())
	roles = append(roles, role.NewHunter())
	// 所有身份生成完毕
	// 将身份洗牌之后按顺序给予玩家
	for i := len(roles) - 1; i >= 1; i-- {
		r := rand.Intn(i + 1) // [0, i]
		roles[i], roles[r] = roles[r], roles[i]
	}

	players := make(Players, 0, len(roles))
	for i, r := range roles {
		players = append(players, &Player{
			ID:   i + 1,
			Role: r,
		})
	}
	return players
}

func (g *Game) Play() error {
	g.printGameInfo()
	NewStages(g).Play()
	g.printGameInfo()
	return nil
}

func (g *Game) IsOver() (bool, int) {
	if len(g.players.GetVillagers().GetAlive()) == 0 {
		return true, role.BadMan
	}
	if len(g.players.GetGods().GetAlive()) == 0 {
		return true, role.BadMan
	}
	if len(g.players.GetWerewolves().GetAlive()) == 0 {
		return true, role.GoodMan
	}
	return false, 0
}

func (g *Game) printGameInfo() {
	fmt.Println("=========游戏信息=========")
	for _, player := range g.players {
		alive := "存活"
		if !player.Role.IsAlive() {
			alive = "死亡"
		}
		fmt.Printf("%d 号玩家：%s，%s。\n", player.ID, player.Role, alive)
	}
	fmt.Println("========================")
}
